import json

from view.com_0.content_frame_base import ContentFrameBase, init_tool_button
from boot import Union, QWidget, QHBoxLayout, AvatarWidget, Qt, QLabel, QVBoxLayout, QEvent, QFileDialog, IMG_ROOT_DIR, os
from utils.file import *
from db.db_customer import DBCustomer
from boot import CurrentSelectedID, ListWidgetObject, QPixmap, Signal, FontFamily
from view.widget.qq9_line import QQ9Line
from view.widget.qq9_info_widget import QQ9InfoWidget
from view.widget.qq9_layout_widget import QQ9HLayoutWidget
from view.widget.qq9_button import QQ9PushButton, QQ9PrimaryPushButton
from db.db_bill import DBBill
from db.db_sale import DBSale
from utils.format import amount_format


__all__ = ["CustomerContentFrame"]


class CustomerContentFrame(ContentFrameBase):

    @init_tool_button
    def __init__(self, parent: Union[QWidget, None] = None):
        super().__init__(parent)

        # 头像
        self.avatar_info_widget = _AvatarInfoWidget()
        self.content_frame.main_v_layout.addWidget(self.avatar_info_widget)

        # 水平直线
        self.line = QQ9Line()
        self.content_frame.main_v_layout.addWidget(self.line)

        # 手机号码
        self.phone_info_widget = QQ9InfoWidget(title="手机号码", icon_path=IMG_ROOT_DIR + "/phone.png")
        self.content_frame.main_v_layout.addWidget(self.phone_info_widget)

        # 公司名称
        self.company_info_widget = QQ9InfoWidget(title="公司名称", icon_path=IMG_ROOT_DIR + "/company.png")
        self.content_frame.main_v_layout.addWidget(self.company_info_widget)

        number_style = f"""
            font-family: "{FontFamily.wechat_sans}";
            font-size: 16px;
            color: #1890FF;
            background-color: transparent;
            """

        # 发货金额
        self.amount_info_widget_01 = QQ9InfoWidget(title="发货金额", icon_path=IMG_ROOT_DIR + "/支付.png")
        self.amount_info_widget_01.content_label.setStyleSheet(number_style)
        self.amount_info_widget_01.set_info("0")
        self.content_frame.main_v_layout.addWidget(self.amount_info_widget_01)

        # 回款金额
        self.receipt_info_widget_02 = QQ9InfoWidget(title="回款金额", icon_path=IMG_ROOT_DIR + "/支付.png")
        self.receipt_info_widget_02.content_label.setStyleSheet(number_style)
        self.receipt_info_widget_02.set_info("0")
        self.content_frame.main_v_layout.addWidget(self.receipt_info_widget_02)

        # 剩余回款
        self.remain_info_widget_03 = QQ9InfoWidget(title="剩余回款", icon_path=IMG_ROOT_DIR + "/支付.png")
        self.remain_info_widget_03.content_label.setStyleSheet(number_style)
        self.remain_info_widget_03.set_info("0")
        self.content_frame.main_v_layout.addWidget(self.remain_info_widget_03)

        # 发货批次
        self.times_info_widget_04 = QQ9InfoWidget(title="发货批次", icon_path=IMG_ROOT_DIR + "/货车.png")
        self.times_info_widget_04.content_label.setStyleSheet(number_style)
        self.times_info_widget_04.set_info("0")
        self.content_frame.main_v_layout.addWidget(self.times_info_widget_04)

        # 发货件数
        self.number_info_widget_05 = QQ9InfoWidget(title="发货件数", icon_path=IMG_ROOT_DIR + "/业绩任务-进件数量.png")
        self.number_info_widget_05.content_label.setStyleSheet(number_style)
        self.number_info_widget_05.set_info("0")
        self.content_frame.main_v_layout.addWidget(self.number_info_widget_05)

    def set_info(self, cust_id: str = "", cust_name: str = "", cust_tel: str = "", cust_company: str = "", cust_icon: str = ""):
        # 基本信息
        self.avatar_info_widget.set_avatar_info(cust_id, cust_icon, cust_name)
        self.phone_info_widget.set_info(cust_tel)
        self.company_info_widget.set_info(cust_company)

        # 账目信息
        with DBSale() as sale_db:
            with DBBill() as bill_db:
                # 获取本人的所有数据
                sale_data = sale_db.get_all_info(cust_id = CurrentSelectedID.customer_selected_id)
                bill_data = bill_db.get_all_info(cust_id = CurrentSelectedID.customer_selected_id)

                number_01: int = 0
                number_02: int = 0
                number_03: int = 0
                number_04: int = len(sale_data)
                number_05: int = 0

                # 计算（ 01发货金额， 04发货批次，05发货件数）
                if number_04:
                    for sale in sale_data:
                        for row in json.loads(sale["sale_list"])["content"]:
                            # 1.全部发货金额累加
                            number_01 += int(row[5]) if row[5] != "" else 0
                            # 2.全部发货件数累加
                            number_05 += int(row[1]) if row[1] != "" else 0

                # 计算（02回款金额， 03剩余回款）
                if len(bill_data):
                    for bill in bill_data:
                        number_02 += int(bill["bill_amount"]) if bill["bill_amount"] != "" else 0

                number_03 = number_01 - number_02

                # 写入信息
                self.amount_info_widget_01.set_info("￥" + amount_format(str(number_01)))
                self.receipt_info_widget_02.set_info("￥" + amount_format(str(number_02)))
                self.remain_info_widget_03.set_info("￥" + amount_format(str(number_03)))
                self.times_info_widget_04.set_info(str(number_04))
                self.number_info_widget_05.set_info(str(number_05))


class _AvatarInfoWidget(QWidget):

    sgn_avatar_changed = Signal()

    def __init__(self, parent: Union[QWidget, None] = None):
        super().__init__(parent)

        # 主水平布局
        self.main_h_layout = QHBoxLayout()
        self.main_h_layout.setContentsMargins(20, 0, 0, 0)
        self.main_h_layout.setSpacing(20)
        self.setLayout(self.main_h_layout)

        # 头像
        self.avatar_widget = AvatarWidget()
        self.avatar_widget.setCursor(Qt.PointingHandCursor)
        self.avatar_widget.setRadius(35)
        self.main_h_layout.addWidget(self.avatar_widget)

        # 创建遮罩层
        self.overlay = QWidget(self.avatar_widget)
        self.overlay.setStyleSheet("background-color: rgba(128, 128, 128, 150); border-radius: 35px;")
        self.overlay.hide()
        self.overlay.setAttribute(Qt.WA_TransparentForMouseEvents)  # 允许鼠标事件穿透

        # 添加居中文字
        self.overlay_label = QLabel("更换头像", self.overlay)
        self.overlay_label.setAlignment(Qt.AlignCenter)
        self.overlay_label.setStyleSheet("font-family: '微软雅黑'; color: white; font-size: 13px; background-color: transparent;")

        # 设置遮罩层布局
        overlay_layout = QVBoxLayout(self.overlay)
        overlay_layout.addWidget(self.overlay_label, 0, Qt.AlignCenter)

        # 安装事件过滤器
        self.avatar_widget.installEventFilter(self)

        # 插入文本
        self.text_widget = _TextWidget()
        self.main_h_layout.addWidget(self.text_widget)

    def eventFilter(self, obj, event):
        if obj == self.avatar_widget or obj == self.overlay:
            if event.type() == QEvent.Enter:
                self.overlay.setGeometry(self.avatar_widget.rect())
                self.overlay.show()
            elif event.type() == QEvent.Leave:
                self.overlay.hide()

        # 处理鼠标点击事件
        if event.type() == QEvent.MouseButtonPress:
            if obj == self.avatar_widget or obj == self.overlay:
                self.sgn_avatar_changed.emit()
                return True  # 表示事件已处理

        return super().eventFilter(obj, event)

    @staticmethod
    def select_avatar_image():
        """打开文件选择对话框"""
        file_dialog = QFileDialog()
        file_dialog.setWindowTitle("选择头像")
        file_dialog.setNameFilter("Images (*.png *.jpg *.jpeg *.bmp *.gif)")
        file_dialog.setFileMode(QFileDialog.ExistingFile)

        if file_dialog.exec_():
            selected_files = file_dialog.selectedFiles()
            if selected_files:
                # 1.获取选择的图片路径
                file_path = selected_files[0]
                # 2.复制图片到指定目录
                copy_file(file_path, dst_dir := IMG_ROOT_DIR + "/avatar/")
                # 3.存储至数据库
                with DBCustomer() as cust_db:
                    # 4.更新头像
                    cust_db.update_icon(cust_icon=dst_dir + os.path.basename(file_path), cust_id=CurrentSelectedID.customer_selected_id)
                    # 5.刷新List
                    ListWidgetObject.customer_list_widget.edit_list_widget(cust_db.get_all_info_)

    def set_avatar_info(self, cust_id: str = "", icon_path: str = "", cust_name: str = ""):
        # 设置头像信息
        # 1.加载头像
        self.avatar_widget.setImage(icon_path)
        self.avatar_widget.setRadius(35)

        # 2.更新文本
        self.text_widget.name_label.setText(cust_name)
        self.text_widget.cust_id.setText("ID  " + cust_id)


class _TextWidget(QWidget):

    def __init__(self, cust_name: str = "", cust_id: str = "未知", parent=None):
        super().__init__(parent=parent)

        # 垂直布局
        self.v_layout = QVBoxLayout()
        self.v_layout.setContentsMargins(3, 15, 0, 15)
        self.v_layout.setSpacing(5)
        self.setLayout(self.v_layout)
        self.v_layout.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)

        # 文本
        self.name_label = QLabel(cust_name)
        self.name_label.setStyleSheet(
            """
            font-family: "微软雅黑";
            font-size: 18px;
            color: #111111;
            background-color: transparent;
            """
        )

        # 公司名称
        self.cust_id = QLabel(cust_id)
        self.cust_id.setStyleSheet(
            f"""
            font-family: "微软雅黑";
            font-size: 13px;
            color: #919191;
            background-color: transparent;
            """
        )

        # 图片
        self.img_label = QLabel()
        self.img_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        self.img_label.setContentsMargins(0, 0, 0, 0)
        self.img_label.setPixmap(QPixmap(IMG_ROOT_DIR + "/vip.png"))

        self.v_layout.addWidget(self.name_label)
        self.v_layout.addWidget(self.cust_id)
        self.v_layout.addWidget(self.img_label)